//
//  BSKHomeVCToLoginVCanimation.m
//  MicroMemory
//
//  Created by rimi on 16/7/11.
//  Copyright © 2016年 BlueSky. All rights reserved.
//

#import "BSKHomeVCToLoginVCanimation.h"
#import "BSKHomeViewController.h"
#import "BSKLoginViewController.h"
#import "BSKconsts.h"


@implementation BSKHomeVCToLoginVCanimation
-(NSTimeInterval)transitionDuration:(id<UIViewControllerContextTransitioning>)transitionContext{
	return 0.7;
}

-(void)animateTransition:(id<UIViewControllerContextTransitioning>)transitionContext{
	BSKHomeViewController * homeVC = [transitionContext viewControllerForKey:UITransitionContextFromViewControllerKey];
	BSKLoginViewController * loginVC = [transitionContext viewControllerForKey:UITransitionContextToViewControllerKey];
	
	CGFloat screenWidth = [UIScreen mainScreen].bounds.size.width;
	CGFloat screenHeight = [UIScreen mainScreen].bounds.size.height;
	UIView * headImageView =[[homeVC menuHeadImageView] snapshotViewAfterScreenUpdates:NO];
	UIView * toView = [loginVC.view snapshotViewAfterScreenUpdates:YES];
	toView.hidden = YES;
	homeVC.menuHeadImageView.hidden = YES;
	
	UIView * stageView = [transitionContext containerView];
	
	headImageView.center = homeVC.menuHeadImageView.center;
	[stageView addSubview:homeVC.view];
	[stageView addSubview:headImageView];
	[stageView addSubview:toView];
	
	
	[UIView animateWithDuration:[self transitionDuration:transitionContext]*0.4 delay:0 options:UIViewAnimationOptionCurveEaseInOut animations:^{
		headImageView.center = CGPointMake(screenWidth/2, StatusBarHeight + NavigationBarHeight + 85);
	} completion:^(BOOL finished) {
		
		CALayer * masklayer = [CALayer layer];
		masklayer.frame = headImageView.frame;
		masklayer.cornerRadius = masklayer.bounds.size.width/2;
		masklayer.backgroundColor = [UIColor blackColor].CGColor;
		masklayer.shadowColor = [UIColor blackColor].CGColor;
		masklayer.shadowOffset = CGSizeMake(0, 0);
		masklayer.shadowOpacity = 1;
		masklayer.shadowRadius = 5;
		toView.layer.mask = masklayer;
		toView.hidden = NO;
		CGFloat scale = sqrt(screenWidth*screenWidth/4 + (screenHeight-145)*(screenHeight-145))/masklayer.cornerRadius;
		CABasicAnimation * animation = [CABasicAnimation animationWithKeyPath:@"transform.scale"];
		animation.toValue = @(scale);
		animation.duration = [self transitionDuration:transitionContext]*0.6;
		animation.removedOnCompletion = NO;
		animation.fillMode = kCAFillModeForwards;
		
		[masklayer addAnimation:animation forKey:@"animation"];

		[UIView animateWithDuration:[self transitionDuration:transitionContext]*0.6 animations:^{
			headImageView.alpha = 0;
		} completion:^(BOOL finished) {
			homeVC.menuHeadImageView.hidden = NO;
			[headImageView removeFromSuperview];
			[masklayer removeFromSuperlayer];
			[transitionContext completeTransition:YES];
			[stageView addSubview:loginVC.view];
			[toView removeFromSuperview];
		}];
	}];
}

@end
